<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="getInfo.query"
            clearable
            @clear="getUserlist"
          >
            <!-- 清空时刷新表单 -->
            <el-button slot="append" icon="el-icon-search" @click="getUserlist"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table :data="userList" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <!-- 第一列索引列，添加type为index -->
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <!-- 用户状态 -->
          <template slot-scope="scope">
            <el-switch
              active-color="#13ce66"
              inactive-color="grey"
              v-model="scope.row.mg_state"
              @change="changeState(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" class="control" width="180">
          <!-- 修改 -->
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="light"
              content="修改"
              placement="top-end"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-setting"
                size="mini"
                @click="showEdit(scope.row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除 -->
            <el-tooltip
              class="item"
              effect="light"
              content="删除"
              placement="top-end"
              :enterable="false"
            >
              <!-- 删除确认提示messageBox弹框 -->
              <el-button
                type="warning"
                icon="el-icon-delete"
                size="mini"
                @click="removeUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 分配角色 -->
            <el-tooltip
              class="item"
              effect="light"
              content="分配角色"
              placement="top-end"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-edit"
                size="mini"
                @click="showSetRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="changeSize"
        @current-change="changePage"
        :page-sizes="[1, 2, 4, 5]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
      <el-form
        :model="userForm"
        status-icon
        :rules="rules"
        ref="userFormRef"
        label-width="100px"
        class="demo-userForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="userForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 手机和邮箱用自定义校验规则 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model.number="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reset()">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editVisible" width="50%" @close="hideEdit">
      <!-- close事件，关闭后执行某些事情 -->
      <el-form
        :model="editForm"
        status-icon
        :rules="rules"
        ref="editFormRef"
        label-width="100px"
        class="demo-userForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <!--手机邮箱还是用user的自定义校验规则 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model.number="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible=false">取 消</el-button>
        <el-button type="primary" @click="doEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoledialogVisible" @close="delSelectRole">
      <div class="roleBox">
        当前用户：
        <span>{{roleInfo.username}}</span>
      </div>
      <div class="roleBox">
        当前角色：
        <span>{{roleInfo.role_name}}</span>
      </div>
      <div class="roleBox">
        分配新角色：
        <!-- 选择器 -->
        <el-select v-model="roleID" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doSetRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 定义手机和邮箱的校验规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^[1][3-9]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机号'))
    }
    return {
      getInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      dataNum: '',
      total: 0,
      dialogVisible: false,
      editVisible: false,
      // 添加用户的表单数据
      userForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {},
      rules: {
        username: [
          { required: true, message: '用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setRoledialogVisible: false,
      // 点击分配角色获取的信息
      roleInfo: {},
      // 现有的角色列表
      roleList: [],
      roleID: ''
    }
  },
  created() {
    this.getUserlist()
  },
  methods: {
    async getUserlist() {
      const { data: ret } = await this.$http.get('users', {
        params: this.getInfo
      })
      this.userList = ret.data.users
      console.log(this.userList)
      this.total = ret.data.total
    },
    changeSize(e) {
      // 每页个数发生变化时触发
      console.log(e)
      this.getInfo.pagesize = e
      this.getUserlist()
    },
    changePage(e) {
      // 点击页码时触发
      console.log(e)
      this.getInfo.pagenum = e
      this.getUserlist()
    },
    async changeState(info) {
      // 改变用户状态
      const { data: ret } = await this.$http.put(
        'users/' + info.id + '/state/' + info.mg_state
      )
      console.log(ret)
      if (ret.meta.status !== 200) {
        info.mg_state = !info.mg_state // 不成功页面上就不能修改，这里用了v-model双向数据绑定
        return this.$message.error(ret.meta.msg)
      }
      this.$message.success(ret.meta.msg)
    },
    addUser() {
      // 添加用户
      this.$refs.userFormRef.validate(async val => {
        if (!val) return
        const { data: ret } = await this.$http.post('users', this.userForm)
        if (ret.meta.status !== 201) return this.$message.error(ret.meta.msg)
        this.$message.success(ret.meta.msg)
        console.log(ret)
        this.getUserlist()
        this.reset()
      })
    },
    reset() {
      // 清空表单
      this.dialogVisible = false
      this.$refs.userFormRef.resetFields()
    },
    async showEdit(id) {
      // 显示修改界面
      this.editVisible = true
      console.log(id)
      const { data: ret } = await this.$http.get('users/' + id)
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.message)
      this.editForm = ret.data
      console.log('用户数据', ret)
    },
    doEdit() {
      // 提交修改数据
      this.editVisible = false
      this.$refs.editFormRef.validate(async val => {
        console.log(val)
        if (!val) return
        const { email, mobile } = this.editForm
        console.log(email, mobile)
        const { data: ret } = await this.$http.put(
          'users/' + this.editForm.id,
          { email, mobile }
        )
        if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
        this.$message.success(ret.meta.msg)
        console.log('修改响应', ret)
        this.getUserlist()
      })
    },
    hideEdit() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除确认框配置
    removeUser(id) {
      // messageBox.$confirm要挂载在vue原型上
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: ret } = await this.$http.delete('users/' + id)
          console.log(ret)
          if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
          this.$message({
            type: 'success',
            message: ret.meta.msg
          })
          this.getUserlist()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async showSetRoleDialog(info) {
      // 显示分配角色对话框
      console.log(info)
      this.setRoledialogVisible = true
      this.roleInfo = info
      // 渲染可选择的角色列表
      const { data: ret } = await this.$http.get('roles')
      console.log(ret)
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.roleList = ret.data
    },
    async doSetRoles() {
      // 完成分配角色
      this.setRoledialogVisible = false
      // 发请求
      if (!this.roleID) return this.$message.error('未选择角色')
      console.log(this.roleID)
      const { data: ret } = await this.$http.put(
        `users/${this.roleInfo.id}/role`,
        {
          rid: this.roleID
        }
      )
      console.log(ret)
      if (ret.meta.status !== 200) return this.$message.error(ret.meta.msg)
      this.$message.success(ret.meta.msg)
      // 刷新列表
      this.getUserlist()
    },
    delSelectRole() {
      // 关闭对话框时清空选择
      this.roleID = ''
    }
  }
}
</script>

<style>
.el-card {
  box-shadow: 0 1px 1px black;
}
.el-table {
  margin: 10px 0;
}
.control {
  display: flex;
}
.roleBox {
  margin-top: 15px;
  font-size: 16px;
}
</style>
